package alo;

/**
 * 二分法查找一个数
 */
public class L_BinarySearch {
    public static void main(String[] args) {
        double[] arr = {2.0, 2.1, 9, 5.02, 6, 3.04, 8, 4, 0.3, 5, 3.22, 6.2};
        double[] sorted = L_BubbleSort.bubbleSort(arr, false);
        for (double v : sorted) {
            System.out.print(" "+v);
        }
        int i = binarySearch(8, sorted);
        System.out.println(i);

    }

    private static int binarySearch(int low, int high, double pat, double[] src) {
        if (pat < src[low] || pat > src[high]) return -1;
        else {
            int mid = (low + high) / 2;
            if (src[mid] == pat) return mid;
            else if (src[mid] < pat) return binarySearch(mid + 1, high, pat, src);
            else return binarySearch(low, mid - 1, pat, src);
        }
    }

    /**
     * 二分查找法
     *
     * @param value
     * @param src
     * @return
     */
    public static int binarySearch(double value, double[] src) {
        return binarySearch(0, src.length - 1, value, src);
    }
}
